package cm.tl.pms.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class SystemChecker {

    /**
     * 检查当前操作系统是否为 Linux 并且 IP 地址是否匹配
     *
     * @param targetIp 目标 IP 地址
     * @return 如果操作系统为 Linux 并且 IP 地址匹配返回 true，否则返回 false
     */
    public boolean checkIsLinuxAndIp(String targetIp) {
        return isLinux() && isIpMatch(targetIp);
    }

    /**
     * 检查当前机器的 IP 地址是否为指定的 IP 地址
     *
     * @param targetIp 目标 IP 地址
     * @return 如果 IP 地址匹配返回 true，否则返回 false
     */
    public static boolean isIpMatch(String targetIp) {
        boolean isIpMatch = false;
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().equals(targetIp)) {
                        isIpMatch = true;
                        break;
                    }
                }
                if (isIpMatch) {
                    break;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return isIpMatch;
    }

    /**
     * 检查当前操作系统是否为 Linux
     *
     * @return 如果是 Linux 返回 true，否则返回 false
     */
    public static boolean isLinux() {
        String osName = System.getProperty("os.name").toLowerCase();
        return osName.contains("linux");
    }

    public static void main(String[] args) {
        System.out.println("Is Linux and IP is 192.168.1.38: " + SystemChecker.isLinux());
    }
}